#include <sys/shm.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#define SHM_NAME "./shm_file"
#define SHMSIZE 4096
int shmid;
void *addr;
void sighandle(int sig)
{
    shmdt(addr);
    shmctl(shmid,IPC_RMID,NULL);
    exit(1);
}
int main(int argc,char **argv)
{
 
    key_t key;
    key=ftok(SHM_NAME,'k');
    signal(SIGINT,sighandle);
    shmid=shmget(key,SHMSIZE,0655|IPC_CREAT);
    if(shmid<0)
    {
        perror("shmget error\n");
        exit(1);
    }
    printf("%x\n",key);
    printf("%d\n",shmid);
    pid_t pid;
    pid =fork();
    if(pid == 0)
    {
        void *addr=shmat(shmid,NULL,0);
        char buff[1024];
        while(1)
        {
            memset(buff,0,sizeof(buff));
            scanf("%s",buff);
            memcpy(addr,buff,strlen(buff));
        }
    }
    else if(pid >0)
    {
        void *addr=shmat(shmid,NULL,0);
        char buff[1024];
         while(1)
        {
            memset(buff,0,sizeof(buff));
            
            memcpy(buff,addr,sizeof(buff));
            printf("%s\n",buff);
            sleep(1);
        }
    }
    
    return 0;
}